'ui';
importClass(java.io.File);
let safUtil = require('./saf.js');
let tdir = null;
let path;
ui.layout(
    <vertical>
        <text id="path" text="文件名" textSize="16sp" textColor="#000000" marginLeft="8dp"
        gravity="center" maxLines="2" ellipsize="end" />
        <ScrollView id="list" >
        </ScrollView>
    </vertical>)

ui.emitter.on('resume', () => {
    let data = safUtil.get_data_documentFile(activity);
    tdir = data;
    path = new File('/sdcard/Android/data');
    ui.path.text(path.getPath());
    createView_and_Bind(data.listFiles(), ui.list);
});
dialogs.alert('提示','从安卓11开始，谷歌限制了Android/data目录的访问权限，'+
'普通应用无法直接使用java.io访问该目录的文件，'+
'但是可以通过安卓提供的SAF框架读取文件，需要跳转页面授权').then(()=>{
    safUtil.getPermission(activity);
})

let xml = (
    <card w="*"  margin="0 2" cardCornerRadius="2dp"
    cardElevation="1dp" foreground="?selectableItemBackground">
    <horizontal w="*">
        <img id="icon" w="50dp" h="50dp" scaleType="fitXY" tint="#77ca28" />
        <text id="name" text="文件名" h="*" textSize="16sp" textColor="#373737" marginLeft="8dp"
        gravity="center" maxLines="2" ellipsize="end" />
    </horizontal>
    </card>
);

function createView_and_Bind(data_list, viewGroup) {
    let i = 0;
    viewGroup.removeAllViews();
    let ver = ui.inflate(
        <vertical padding="16">
        </vertical>, viewGroup, true);
    let sid = setInterval((item) => {
        if (i >= data_list.length) {
            return clearInterval(sid);
        }
        let item = data_list[i];
        let icon = item.isDirectory() ? "ic_folder_black_48dp" :
            "ic_insert_drive_file_black_48dp";
        let view = ui.inflate(xml, ver, true);
        if (item.isDirectory()) {
            view.click(() => {
                clickDir(item);
            })
        } else {
            view.click(() => {
                clickFile(item);
            })
        }
        view.name.setText(item.getName());
        view.icon.setSource(icon);
        i++;
    }, 0)
}

function clickDir(documentFile) {
    tdir = documentFile;
    path = new File(path, documentFile.getName());
    ui.path.text(path.getPath());
    createView_and_Bind(documentFile.listFiles(), ui.list)
}

function clickFile(documentFile) {
    rawInput("拷贝 " + documentFile.getName() + '到:', "/sdcard/Download").then(path => {
        if (!path) return;
        let file = new File(path,documentFile.getName());
        let downloadDialog = dialogs.build({
            title: "拷贝中",
            progress: {
                max: -1,
                horizontal: true
            },
            cancelable: true
        }).show();
        safUtil.saveDocumentFile(activity,documentFile,file.getPath(),(b)=>{
            ui.run(()=>{
                downloadDialog.dismiss();
                toast('拷贝'+(b?'成功':'失败'));
            })
        })
    });
}
var isCanFinish = false;
var isCanFinishTimeout;
ui.emitter.on("back_pressed", e => {
    let paren = tdir.getParentFile();
    if (paren != null) {
        tdir = paren;
        path = path.getParentFile();
        ui.path.text(path.getPath());
        createView_and_Bind(paren.listFiles(), ui.list);
        return e.consumed = true;
    }
    if (!isCanFinish) {
        isCanFinish = true;
        toast("在按一次退出");
        isCanFinishTimeout = setTimeout(() => {
            isCanFinish = false;
        }, 2000);
        e.consumed = true;
    } else {
        clearTimeout(isCanFinishTimeout);
        e.consumed = false;
    };
});